const http = require('http');
const httpProxy = require('http-proxy');

// 1. 创建代理实例
const proxy = httpProxy.createProxyServer({
  target: 'http://192.168.122.82:31000', // Loki 默认地址
  changeOrigin: true,              // 修改请求头中的 Host 为目标地址[6,7](@ref)
});

// 2. 错误处理
proxy.on('error', (err, req, res) => {
  res.writeHead(500, { 'Content-Type': 'text/plain' });
  res.end('Proxy Error: ' + err.message);
});

// 3. 添加CORS支持
proxy.on('proxyRes', (proxyRes, req, res) => {
  // 添加CORS头
  proxyRes.headers['Access-Control-Allow-Origin'] = '*'; // 允许所有来源访问，生产环境中应该限制为特定域名
  proxyRes.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS';
  proxyRes.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization';
  proxyRes.headers['Access-Control-Max-Age'] = '86400'; // 预检请求缓存24小时
});

// 4. 启动代理服务器
const server = http.createServer((req, res) => {
  // 处理预检请求(OPTIONS)
  if (req.method === 'OPTIONS') {
    res.writeHead(200, {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
      'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Authorization',
      'Access-Control-Max-Age': '86400'
    });
    res.end();
    return;
  }
  
  // 可选：添加子路径处理（如 /loki）
//   if (req.url.startsWith('/myloki')) {
//     req.url = req.url.replace('/myloki', ''); // 移除子路径后再转发
//   }
  proxy.web(req, res); // 转发请求到 Loki
});

server.listen(3100,'0.0.0.0', () => {
  // log all available ipv4 addresses
  const os = require('os');
  const interfaces = os.networkInterfaces();
  for (const devName in interfaces) {
    const iface = interfaces[devName];
    for (let i = 0; i < iface.length; i++) {
      const alias = iface[i];
      if (alias.family === 'IPv4' && alias.address !== 'IP_ADDRESS' && !alias.internal) {
        console.log(`Proxy server is running on ${alias.address}:3100`);
      }
    }
  }
});